import React, { FC, ReactElement, useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux'
import TdInput from './Input'
import TdList from './List'
import { ITodo, ACTION_TYPE } from './typings';

const TodoList: FC = (): ReactElement => {
  // const [todoList, setTodoList] = useState<ITodo[]>([])
  const todoList = useSelector((state: any) => {
      return state.getIn(['todolist', 'todoList'])
    }
  )
  const dispatch = useDispatch();

  // useEffect(() => {
  //   const todoList = JSON.parse(localStorage.getItem('todolist') || '[]');
  //   dispatch({
  //     type: ACTION_TYPE.INIT_TODOLIST,
  //     payload: todoList
  //   }) 
  //   console.log(todoList);
  // }, []) // 这里没有依赖 

  // useEffect(() => {
  //   localStorage.setItem('todolist', JSON.stringify(state.todoList));
  // }, [state.todoList])

  const addTodo = useCallback((todo: ITodo): void => {
    // setTodoList(todoList => [...todoList, todo]);
    dispatch({
      type: ACTION_TYPE.ADD_TODO,
      payload: todo
    })
  }, [dispatch])
  
  const removeTodo = useCallback(
    (id: number): void => {
      dispatch({
        type: ACTION_TYPE.REMOVE_TODO,
        payload: id
      })
    },
    [dispatch],
  )

  const toggleTodo = useCallback(
    (id: number): void => {
      dispatch({
        type: ACTION_TYPE.TOGGLE_TODO,
        payload: id
      })
    },
    [dispatch],
  )

  return (
    <div>
      <h2 style={{ fontSize: '20px', margin: '0 0 8px 0' }}>TODOLIST</h2>
      <TdInput 
         addTodo={ addTodo }
         todoList={ todoList }
      ></TdInput>
      <TdList
        todoList={ todoList }
        removeTodo={ removeTodo }
        toggleTodo={ toggleTodo }
      ></TdList>
    </div>
  )
} 

export default TodoList;
